/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { ArkAssignStmt, ArkInstanceFieldRef, ArkNormalBinopExpr, Constant, Local, MethodSignature, Stmt, ViewTreeNode } from 'arkanalyzer/lib';
import { ArkClass } from 'arkanalyzer/lib/core/model/ArkClass';
import Logger, { LOG_MODULE_TYPE } from 'arkanalyzer/lib/utils/logger';
import { BaseChecker, BaseMetaData } from '../BaseChecker';
import { Rule, Defects, ClassMatcher, MatcherTypes, MatcherCallback, CheckerUtils } from '../../Index';
import { ViewTreeTool } from '../../utils/checker/ViewTreeTool';
import { IssueReport } from '../../model/Defects';

const logger = Logger.getLogger(LOG_MODULE_TYPE.HOMECHECK, 'FetchBuildConstantExpressionCheck');
const gMetaData: BaseMetaData = {
    severity: 1,
    ruleDocPath: 'docs/avoid-constant-expression-in-build.md',
    description: 'Extract the constant expression in the render function build to reduce the number of calculations.'
};
let viewTreeTool: ViewTreeTool = new ViewTreeTool();

export class AvoidConstantExpressionInBuild implements BaseChecker {
    readonly metaData: BaseMetaData = gMetaData;
    public rule: Rule;
    public defects: Defects[] = [];
    public issues: IssueReport[] = [];

    private clsMatcher: ClassMatcher = {
        matcherType: MatcherTypes.CLASS,
        hasViewTree: true
    };

    public registerMatchers(): MatcherCallback[] {
        const matchClazzCb: MatcherCallback = {
            matcher: this.clsMatcher,
            callback: this.check
        };
        return [matchClazzCb];
    }

    public check = (arkClass: ArkClass): void => {
        let viewTreeRoot = arkClass.getViewTree()?.getRoot();
        if (!viewTreeRoot) {
            return;
        }
        this.traverseViewTree(viewTreeRoot, arkClass);
    };

    private traverseViewTree(viewTreeRoot: ViewTreeNode, arkClass: ArkClass): void {
        if (viewTreeTool.hasTraverse(viewTreeRoot)) {
            return;
        }
        for (let [key, vals] of viewTreeRoot.attributes) {
            if (key === 'create') {
                continue;
            }
            if (vals[1].length < 2) {
                continue;
            }
            this.checkSyncBlurByVals(vals);
        }
        if (viewTreeRoot.children.length > 0) {
            for (let child of viewTreeRoot.children) {
                this.traverseViewTree(child, arkClass);
            }
        }
    }

    private checkSyncBlurByVals(vals: [Stmt, (Constant | ArkInstanceFieldRef | MethodSignature)[]]): void {
        let invoker = CheckerUtils.getInvokeExprFromStmt(vals[0]);
        if (!invoker) {
            return;
        }
        let arg = invoker.getArg(0);
        if (!(arg instanceof Local)) {
            return;
        }
        let stmt = arg.getDeclaringStmt();
        if (stmt instanceof ArkAssignStmt) {
            let rightOp = stmt.getRightOp();
            if (rightOp instanceof ArkNormalBinopExpr) {
                if (this.isConstantNumber(rightOp)) {
                    this.reportIssue(stmt, arg);
                }
            }
        }
    }

    private isConstantNumber(rightOp: ArkNormalBinopExpr): boolean {
        let op1Type = rightOp.getOp1().getType().getTypeString();
        let op2Type = rightOp.getOp2().getType().getTypeString();
        let operator = rightOp.getOperator();
        if (op1Type === 'number' && op2Type === 'number' && ['+', '-', '*', '/', '%', '>>', '<<'].includes(operator)) {
            return true;
        }
        return false;
    }

    private reportIssue(stmt: Stmt, arg: Local): void {
        const severity = this.rule.alert ?? this.metaData.severity;
        const filePath = stmt.getCfg().getDeclaringMethod().getDeclaringArkFile().getFilePath();
        const originPosition = stmt.getOperandOriginalPosition(arg);
        if (!originPosition) {
            return;
        }
        const lineNum = originPosition.getFirstLine();
        const startColumn = originPosition.getFirstCol();
        const endColunm = originPosition.getLastCol();
        let defects = new Defects(lineNum, startColumn, endColunm, this.metaData.description, severity, this.rule.ruleId,
            filePath, this.metaData.ruleDocPath, true, false, false);
        this.issues.push(new IssueReport(defects, undefined));
    }
}